package com.ydj.framework.protocol;

import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Getter
@Setter
@Accessors(chain = true)
public class JsonResult<T> {
    @ApiModelProperty(value = "返回码", required = true, example = "0")
    private Integer code;
    @ApiModelProperty(value = "错误提示，当code不等于0时候才会有", example = "网络异常")
    private String errMsg;
    @ApiModelProperty(value = "data")
    private T data;

    private JsonResult() {}

    /**
     * 成功
     */
    public static JsonResult<?> success() {
        return success(null);
    }

    /**
     * 成功, 有data返回
     */
    public static <T extends JsonBaseResponse> JsonResult<T> success(T data) {
        return new JsonResult<T>()
                    .setCode(JsonResponseCode.OK.getCode())
                    .setData(data);
    }

    /**
     * 普通错误
     */
    public static JsonResult<?> error(String errorMsg) {
        return error(JsonResponseCode.OtherError, errorMsg);
    }

    /**
     * 自定义错误码的错误
     */
    public static JsonResult<?> error(JsonResponseCode code) {
        return new JsonResult<>()
                .setCode(code.getCode())
                .setErrMsg(code.getText());
    }

    /**
     * 自定义错误码的错误
     */
    public static JsonResult<?> error(JsonResponseCode code, String errorMsg) {
        return new JsonResult<>()
                    .setCode(code.getCode())
                    .setErrMsg(errorMsg);
    }

    /**
     * 自定义错误码的错误
     */
    public static JsonResult<?> errorCodeResponse(int errorCode, String errorMsg) {
        return new JsonResult<ErrorCodeRes>()
		            .setCode(JsonResponseCode.OK.getCode())
		            .setData(new ErrorCodeRes(errorCode, errorMsg));

    }
}